package com.gyms.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.classic.okhttp.enums.Enum;
import com.classic.okhttp.services.IUserService;
import com.classic.okhttp.zmoumall.http.ObjectCallback;
import com.classic.okhttp.zmoumall.utils.ToastUtil;
import com.google.gson.Gson;
import com.gyms.R;
import com.gyms.base.MyAutoLayoutActivity;
import com.gyms.bean.CDNConfig;
import com.gyms.manager.DataCenter;
import com.gyms.manager.TitleManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import cn.finalteam.galleryfinal.FunctionConfig;
import cn.finalteam.galleryfinal.GalleryFinal;
import cn.finalteam.galleryfinal.model.PhotoInfo;
import constant.EventConstant;
import glide.ImageLoaderUtils;
import upyun.common.Params;
import upyun.common.ResultBean;
import upyun.common.UploadManager;
import upyun.listener.UpCompleteListener;
import upyun.listener.UpProgressListener;
import utils.DataUtil;
import utils.FileUtils;
import utils.PhotoUtil;
import utils.StringUtils;
import weight.UiEvent;

/**
 * 我的资料 yjl
 */
public class MyInformationActivity extends MyAutoLayoutActivity {
    @BindView(R.id.llayout_edhead)
    LinearLayout llayoutEdhead;
    @BindView(R.id.llayout_edname)
    LinearLayout llayoutEdname;
    @BindView(R.id.llayout_edphone)
    LinearLayout llayoutEdphone;
    @BindView(R.id.llayout_edpassword)
    LinearLayout llayoutEdpassword;
    private final int REQUEST_CODE_GALLERY = 1001;
    @BindView(R.id.profile_image)
    ImageView profileImage;
    FunctionConfig functionConfig;
    @BindView(R.id.tv_nickname)
    TextView tvNickname;
    @BindView(R.id.tv_phone_num)
    TextView tvPhoneNum;
    @BindView(R.id.tv_pass_tip)
    TextView tvPassTip;

    private DataCenter mDataCenter;
    private String userIconStr = "";

    @Override
    protected void setTitleTheme() {
        mTheme = TitleManager.TitleTheme.White;
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_my_information;
    }

    @Override
    protected void initView() {
        createLoadingView("正在上传头像", false);
        mDataCenter = DataCenter.getInstance();
        setTitle("我的资料");
        setBack();
        //配置功能
        functionConfig = new FunctionConfig.Builder()
                .setEnableCamera(true)
                .setEnableEdit(true)
                .setEnableCrop(true)
                .setEnableRotate(true)
                .setCropSquare(true)
                .setForceCrop(false)
                .setEnablePreview(true)
                .build();

        initViewData();
    }

    @Override
    protected void setListener() {
        //注册EventBus
        EventBus.getDefault().register(this);
    }

    @Override
    protected void processLogic() {

    }

    @OnClick({R.id.llayout_edhead, R.id.llayout_edname, R.id.llayout_edpassword})
    public void onClick(View view) {
        Intent intent = null;
        switch (view.getId()) {
            case R.id.llayout_edhead:
                GalleryFinal.openGallerySingle(REQUEST_CODE_GALLERY, functionConfig, mOnHanlderResultCallback);
                break;
            case R.id.llayout_edname:
                intent = new Intent(mContext, EditInfoActivity.class);
                intent.putExtra("lable", "昵称");
                break;
            case R.id.llayout_edpassword:
                if (mDataCenter.getUser() != null) {
                    if (mDataCenter.getUser().getIsSetPwd()) {
                        startActivity(EditPassActivity.class, false);
                    } else {
                        startActivity(FirstEditPassActivity.class, false);
                    }
                } else {
                    ToastUtil.showToast(mContext, "参数错误请重新登录");
                    startActivity(CodeLoginActivity.class, true);
                }
                break;
        }
        if (intent != null) {
            startActivity(intent, false);
        }
    }


    private GalleryFinal.OnHanlderResultCallback mOnHanlderResultCallback = new GalleryFinal.OnHanlderResultCallback() {
        @Override
        public void onHanlderSuccess(int reqeustCode, List<PhotoInfo> resultList) {
            if (resultList != null) {
//                ImageLoaderUtils.displayLocal(mContext, profileImage, resultList.get(0).getPhotoPath());
                try {
                    Bitmap bitmap = PhotoUtil.revitionImageSize(resultList.get(0).getPhotoPath());
                    userIconStr = FileUtils.saveBitmap(bitmap, DataUtil.getUUID());
                } catch (IOException e) {
                    e.printStackTrace();
                }
                alterPhoto(userIconStr);
            }
        }

        @Override
        public void onHanlderFailure(int requestCode, String errorMsg) {
            Toast.makeText(mContext, errorMsg, Toast.LENGTH_SHORT).show();
        }
    };

    public void alterPhoto(String userIconStr) {
        if ("".equals(userIconStr)) {
            ImageLoaderUtils.displayLocal(mContext, profileImage, "");
        } else {
            uploadToYunPhoto(userIconStr);
        }
    }

    private void uploadToYunPhoto(String path) {
        loadingView.show();
        getMyOrderInfo(new File(path));
    }

    //上传图片
    public void getMyOrderInfo(File myRecAudioFile) {
        final Map<String, Object> paramsMap = new HashMap<>();
        //上传空间
        paramsMap.put(Params.BUCKET, CDNConfig.hlcgpic);
        //保存路径，任选其中一个
        paramsMap.put(Params.SAVE_KEY, new StringBuffer().append("/").append(myRecAudioFile.getName()).toString());
        paramsMap.put(Params.EXPIRATION, CDNConfig.EXPIRATION);

        UploadManager.getInstance().formUpload(myRecAudioFile, paramsMap, CDNConfig.uploadKey, completeListener, new UpProgressListener() {
            @Override
            public void onRequestProgress(long bytesWrite, long contentLength) {
                if (bytesWrite == contentLength) {
                    isComplete = true;
                }
            }
        });
    }

    private boolean isComplete;

    //图片上传结束回调，不可为空
    UpCompleteListener completeListener = new UpCompleteListener() {
        @Override
        public void onComplete(boolean isSuccess, String result) {
            if (isSuccess && isComplete) {
                ResultBean resultBean = new Gson().fromJson(result, ResultBean.class);

                ImageLoaderUtils.displayCircleUrl(mContext, profileImage, CDNConfig.DOWN_IMAGE_URL + resultBean.getUrl());

                if (resultBean.getCode() == 200) {
                    //提交图片地址到服务器
                    updateInfo(CDNConfig.DOWN_IMAGE_URL + resultBean.getUrl());
                } else {
                    dialogDis();
                }
            } else {
                dialogDis();
                ToastUtil.showToast(mContext, "图片上传失败");
            }
        }
    };

    /**
     * 填充页面数据
     */
    private void initViewData() {
        if (!StringUtils.isNull(mDataCenter.getUser())) {
            ImageLoaderUtils.displayCircleUrl(mContext, profileImage, mDataCenter.getUser().getImageUrl());
            initTextView();
            if (mDataCenter.getUser().getUserName() != null) {
                tvNickname.setText("" + mDataCenter.getUser().getUserName());
            }
            tvPhoneNum.setText(StringUtils.CS(mDataCenter.getUser().getPhone()));
//            tvPhoneNum.setText(phone.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2"));
        }
    }

    private void initTextView() {
        if (mDataCenter.getUser().getIsSetPwd()) {
            tvPassTip.setText("修改密码");
        }
    }


    private void updateInfo(String value) {
        //fieldType:1头像,2昵称,3密码设置fieldValue:密码需要传md5加密过的字符串)
        IUserService.modifyUser(this, Enum.EnumUserFieldType.Pic, value, false, new ObjectCallback<Object>() {

            @Override
            public void onSuccess(Object response, String message) {
                dialogDis();
                notifeMyinfo();
                ToastUtil.showToast(mContext, "头像上传成功");
            }

            @Override
            public void onErrorT(int code, Object response, String errorMessage) {
                dialogDis();
                ToastUtil.showToast(mContext, errorMessage);
            }

            @Override
            public void onHttpErrorCall(int statusCode) {
                dialogDis();
            }
        });
    }

    /**
     * EventBus 接收事件
     *
     * @param uiEvent
     */
    @Subscribe
    public void getName(UiEvent uiEvent) {
        if (uiEvent.getKey().equals(EventConstant.S_NAME)) {
            tvNickname.setText(uiEvent.getObject().toString());
            notifeMyinfo();
        }
    }

    /**
     * EventBus 接收事件
     *
     * @param uiEvent
     */
    @Subscribe
    public void getPass(UiEvent uiEvent) {
        if (uiEvent.getKey().equals(EventConstant.S_PASS)) {
            initTextView();
        }
    }

    /**
     * 通知刷新我的信息
     */
    private void notifeMyinfo() {
        EventBus.getDefault().post(new UiEvent(EventConstant.S_MYINFO, ""));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);//销毁的时候注销EventBus
    }

    /**
     * 对字符串进行 MD5 加密
     *
     * @param str 待加密字符串
     * @return 加密后字符串
     */
    public static String md5(String str) {
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'a', 'b', 'c', 'd', 'e', 'f'};
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
            md5.update(str.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
        byte[] encodedValue = md5.digest();
        int j = encodedValue.length;
        char finalValue[] = new char[j * 2];
        int k = 0;
        for (int i = 0; i < j; i++) {
            byte encoded = encodedValue[i];
            finalValue[k++] = hexDigits[encoded >> 4 & 0xf];
            finalValue[k++] = hexDigits[encoded & 0xf];
        }

        return new String(finalValue);
    }

}
